package com.sendi.system.action;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import net.sf.json.JSONObject;
import org.hibernate.Query;
import org.hibernate.Session;
 
import com.sendi.system.entity.User;
import com.sendi.system.util.export.ReportTooler;
public class UserAction extends SysAction {
    private Integer  id;
	private String   userId;
	private String   userName;
	private String   password;
 
	private Integer  pwdvalicity;
	private String   createdate;
	private String   pwddate;
	private String   istip;
 
   private String deleterecord;
   private String activestatus;
   public InputStream excelStream;
   public Integer maxlogincount=10;
	public Integer getMaxlogincount() {
	return maxlogincount;
}


public void setMaxlogincount(Integer maxlogincount) {
	this.maxlogincount = maxlogincount;
}


	public UserAction()
	{
		super();
		data_session_name="UserActionListData";
	}
	
	
	public void userInit()
	{
		List datas=null;
		
		if(getSession().getAttribute(data_session_name)!=null)
		{
			datas=(List)getSession().getAttribute(data_session_name);
	 	}
		else
		{
			addUserTosessin();
			datas=(List)getSession().getAttribute(data_session_name);
		}
		this.sortObjectList(datas);
		 
			writeJSONArray(datas);
		 
	}
	public void  exportData()
	{
		HttpServletResponse response=this.getResponse();
       	List datas=null;
	 	if(getSession().getAttribute(data_session_name)!=null)
		{
		  	ReportTooler rt=new ReportTooler("用户信息表",response);
	       	rt.ReportInit();
			datas=(List)getSession().getAttribute(data_session_name);
			String[] title={"用户账号","用户名","密码有效期","创建日期","是否激活"};
			String fileds[]={"userId","userName","pwdvalicity","createdate","isactive"};
	       	try {
				rt.ReportWithList(datas, "用户信息表",title, "yyyy-MM-dd", fileds);
			} catch (RowsExceededException e) {
				e.printStackTrace();
			} catch (WriteException e) {
				e.printStackTrace();
			}
	 	}
	
   }
	public void addUserTosessin()
	{
		List datas=null;
		String hql="from  User";
		 
		datas=serviceSupportImp.findByHQL(hql);
	 
		for(Object o:datas)
		{
			User user=(User) o;
			String istip=user.getIstip();
			user.setIstip((istip!=null&&istip.equalsIgnoreCase("on"))?"是":"否");
	 	}
		getSession().setAttribute(data_session_name,datas);
 	}
	
 
   /*
    * 查询用户
    */
	public void queryUser()
	{
		   try
		   {
			     Session session=serviceSupportImp.getDao().getSessionFactory().openSession();
			 	StringBuffer hql=new StringBuffer("from User where 1=1 ");
				if(userId!=null&&userId.trim().length()>0)
				{
					hql.append(" and  userId like :userId ");
				}
				if(userName!=null&&userName.trim().length()>0)
				{
					hql.append(" and userName like :userName");
				}
				
				   Query query= session.createQuery(hql.toString());
				   if(userId!=null&&userId.trim().length()>0)
					{
					  query.setParameter("userId", "%"+userId+"%");
					}
					if(userName!=null&&userName.trim().length()>0)
					{
				 		  query.setParameter("userName", "%"+userName+"%");
					}
					    List datas=query.list();
					    System.out.println("query size"+datas.size());
				     	getSession().setAttribute(data_session_name,datas);	
				     	writeResponseText("{success:true,msg:'success',datasize:"+datas.size()+"}");
		   			}
		   catch (Exception e) {
			   writeResponseText("{success:false,msg:'failure'}");
				 
		}
		    
		
	}

 
	 public void addUser()
	 {
		 
		 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
		 String current=sdf.format(new Date());
	     this.istip= istip==null?"off":this.istip;
		 User User=new User(userId,userName,password,"1", pwdvalicity,current , current,  istip,"on",maxlogincount);
			
			try {
				serviceSupportImp.save(User);
				getSession().removeAttribute(data_session_name);
				addUserTosessin();
				Object mtuser=this.getServletContext().getAttribute("sendi_sys_user_info");
				if(mtuser!=null)
				{
					HashMap<String,User> usermap=(HashMap<String,User>)mtuser;
					usermap.put(User.getUserId(), User);
				}
				
				writeResponseText("{success:true,msg:'success'}");
		 	} catch (Exception e) {
				writeResponseText("{success:false,msg:'faild',errors:{"+e.getMessage()+"}}");
			  e.printStackTrace();
			}
	 }

	 
	 public void excutModifyQueryuser()
		{
			 
			String hql="from User where 1=1 and id="+this.id; 
		 	List datas=serviceSupportImp.findByHQL(hql);
		  
    	 	User user=(User)datas.get(0);
   		try {
			 	System.out.println("{success:true,datas:"+JSONObject.fromObject(user).toString()+"}");
				writeResponseText("{success:true,datas:"+JSONObject.fromObject(user).toString()+"}");
			} catch (Exception e) {
			    writeResponseText("{success:false,msg:'faild',errors:{"+e.getMessage()+"}}");
			 	e.printStackTrace();
			}
			
		}
		public void excuteModifyuser()
		{
		 	String hql="from User where 1=1 and id="+this.id; 
		 	List datas=serviceSupportImp.findByHQL(hql);
		  	User user=(User)datas.get(0);
		 	user.setIstip(istip==null?"off":istip);
		 	user.setUserId(userId);
		 	user.setPwdvalicity(pwdvalicity);
		 	user.setUserName(userName);
		 	if(!user.getPassword().equals(this.password)) //如果原密码跟现有的密码一样，则不修改日期 
		 	{
		 		user.setPassword(password);
		 		 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
				 String current=sdf.format(new Date());
		 		user.setPwddate(current);
		 	}
		 	user.setMaxlogincount(maxlogincount);
			serviceSupportImp.update(user);
		 	getSession().removeAttribute(data_session_name);
			addUserTosessin();
			
			Object mtuser=this.getServletContext().getAttribute("sendi_sys_user_info");
			if(mtuser!=null)
			{
				HashMap<String,User> usermap=(HashMap<String,User>)mtuser;
				usermap.put(user.getUserId(), user);
			}
			
			writeResponseText("{success:true,msg:'success'}"); 
		}
		/*
		 * 用户密码修改页面
		 */
		public void excuteModifyusersql()
		{
			
		 	String hql="from User where  userId='"+this.userId+"' and password='"+this.userName+"' ";
		 
		 	List datas=serviceSupportImp.findByHQL(hql);
		 	if(datas.size()==0)
		 	{
		 		writeResponseText("{success:false,msg:'user_name_and_pwd_not_match'}"); 
		 		
		 	}
		 	else
		 	{
		 		User user=(User)datas.get(0);
			 	user.setIstip(istip==null?"off":istip);
			  	user.setPwdvalicity(pwdvalicity);
			  	if(!user.getPassword().equals(this.password)) //如果原密码跟现有的密码一样，则不修改日期 
			 	{
			 		 user.setPassword(password);
			 		 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
					 String current=sdf.format(new Date());
			 		user.setPwddate(current);
			 	}
			 
				serviceSupportImp.update(user);
			 	getSession().removeAttribute(data_session_name);
				addUserTosessin();
	 			Object mtuser=this.getServletContext().getAttribute("sendi_sys_user_info");
				if(mtuser!=null)
				{
					HashMap<String,User> usermap=(HashMap<String,User>)mtuser;
					usermap.put(user.getUserId(), user);
				}
				
				writeResponseText("{success:true,msg:'success'}"); 
	 	 	}
 		}
		
		
		
		public void excuteDeleteuser()
		{
			 
		  String hql="delete User where id in ("+deleterecord+")";
		   Session session=serviceSupportImp.getDao().getSessionFactory().openSession();
		  session.beginTransaction();
		  session.createQuery(hql).executeUpdate();
		  session.getTransaction().commit();
		  addUserTosessin();
		  writeResponseText("{success:true,msg:'success'}"); 
			Object mtuser=this.getServletContext().getAttribute("sendi_sys_user_info");
			if(mtuser!=null)
			{
				HashMap<String,User> usermap=(HashMap<String,User>)mtuser;
				String uids[]=deleterecord.replaceAll("'","").split(",");
			 	Iterator<String> it=usermap.keySet().iterator();
				while(it.hasNext())
				{
					String uid=it.next();
					User u=usermap.get(uid);
					for(String b:uids)
					{
						if(u.getId().intValue()==Integer.parseInt(b))
						{
							it.remove();
						}
					}
				}
			}
	 	
		}
		
		public void excuteChangestatus()
		{
			String sql="update user set isactive='"+this.activestatus+"' where id in("+this.deleterecord+")";
			int r=this.excuteUpdate(sql); 
		 
			if(r==-1)
			{
				 writeResponseText("{success:false,msg:'fail to change user status'}"); 
			}
			else
			{
			     addUserTosessin();
				 writeResponseText("{success:true,msg:'success'}"); 
			     Object mtuser=this.getServletContext().getAttribute("sendi_sys_user_info");
					if(mtuser!=null)
					{
						HashMap<String,User> usermap=(HashMap<String,User>)mtuser;
						String uids[]=deleterecord.replaceAll("'","").split(",");
					 	Iterator<String> it=usermap.keySet().iterator();
						while(it.hasNext())
						{
							String uid=it.next();
							User u=usermap.get(uid);
							for(String b:uids)
							{
								if(u.getId().intValue()==Integer.parseInt(b))
								{
									 u.setIsactive(this.activestatus);
								}
							}
						}
					}
			}
			
		}
	public Integer getId() {
		return id;
	}



	public void setId(Integer id) {
		this.id = id;
	}



	public String getUserId() {
		return userId;
	}



	public void setUserId(String userId) {
		this.userId = userId;
	}



	public String getUserName() {
		return userName;
	}



	public void setUserName(String userName) {
		this.userName = userName;
	}



	public String getPassword() {
		return password;
	}



	public void setPassword(String password) {
		this.password = password;
	}


 


	public Integer getPwdvalicity() {
		return pwdvalicity;
	}



	public void setPwdvalicity(Integer pwdvalicity) {
		this.pwdvalicity = pwdvalicity;
	}



	public String getCreatedate() {
		return createdate;
	}



	public void setCreatedate(String createdate) {
		this.createdate = createdate;
	}



	public String getPwddate() {
		return pwddate;
	}



	public void setPwddate(String pwddate) {
		this.pwddate = pwddate;
	}



	public String getIstip() {
		return istip;
	}



	public void setIstip(String istip) {
		this.istip = istip;
	}


	public String getDeleterecord() {
		return deleterecord;
	}


	public void setDeleterecord(String deleterecord) {
		this.deleterecord = deleterecord;
	}


	public String getActivestatus() {
		return activestatus;
	}


	public void setActivestatus(String activestatus) {
		this.activestatus = activestatus;
	}


	public InputStream getExcelStream() {
		return excelStream;
	}


	public void setExcelStream(InputStream excelStream) {
		this.excelStream = excelStream;
	}


 
	

}
